import { defineComponent, ref, onUnmounted, nextTick } from 'vue'
import videojs, { VideoJsPlayer } from 'video.js'
import 'video.js/dist/video-js.css'

import useSize from '@/hooks/useSize'
import { sleep } from '@/utils'
import styles from './styles.module.less'
import icoDown from '@/assets/icons/ico-down.svg'
import icoPlus from '@/assets/icons/ico-plus.svg'

const avatarUrl = 'https://tse1-mm.cn.bing.net/th/id/OIP.-s_quEZK3EmbvD72Ds61eAHaEK?pid=ImgDet&rs=1'

export default defineComponent({
  name: 'VlogListItem',
  props: { data: { type: Object } },

  setup(props) {
    const refVideo = ref<HTMLElement | null>(null)
    let player: VideoJsPlayer | null = null

    // 視頻播放器
    const { elementRef: playerRef, size } = useSize()

    nextTick(async () => {
      if (!refVideo.value || !playerRef.value) return
      await sleep(500)

      player = videojs(refVideo.value, {
        width: size.width,
        height: 0.5 * window.innerWidth,
        controls: true,
        sources: [{ src: '//vjs.zencdn.net/v/oceans.mp4', type: 'video/mp4' }],
        poster: 'https://tse2-mm.cn.bing.net/th/id/OIP.wDPE8rXgJl7EMzd4UpnxugHaD5?pid=ImgDet&rs=1',
      })
    })

    onUnmounted(() => {
      player?.dispose()
    })

    return () => (
      <div id={props.data?.id} class={styles.container}>
        <section class={styles.header_content}>
          <div class={styles.avatar} style={{ backgroundImage: `url("${avatarUrl}")` }}></div>
          <div class={styles.content}>
            <p class={styles.info}>
              <span>蒼藍星</span>
            </p>
            <h2 class={styles.title}>怨虎龍暴怒, 直接送蒼藍星叁貓車!</h2>
          </div>
          <div class={styles.follow}>
            <img src={icoPlus} alt='follow' />
            <span>關注</span>
          </div>
          <div class={styles.menu}>
            <img src={icoDown} alt='menu' />
          </div>
        </section>

        <section ref={playerRef} class={styles.video_wrapper}>
          <video ref={refVideo} class='video-js'></video>
        </section>

        <section class={styles.comments_wrapper}>
          <div class={styles.avatar} style={{ backgroundImage: `url("${avatarUrl}")` }}></div>
          <div class={styles.text}>會噴火的大哥哥,加油啊!</div>
        </section>
      </div>
    )
  },
})
